package com.yuqiangz.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuqiangz.springsecurity.domain.LoginUser;
import com.yuqiangz.springsecurity.domain.User;
import com.yuqiangz.springsecurity.mapper.MenuMapper;
import com.yuqiangz.springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author zhaoyuqiang
 * @create 2024/5/17 7:33
 * @description
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //01 根据前段传来的用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);

        // 02 如果查询不到，直接抛出异常
        if(Objects.isNull(user)){
            throw  new UsernameNotFoundException("用户未查询到");
        }

        // 03 TODO 根据用户查询权限信息，添加到LoginUser中
        // 03-01 先将权限信息写死
        //ArrayList<String> authority = new ArrayList<>(Arrays.asList("test", "admin"));
        // 03-02 从数据库中查询
        List<String> permissionKeyList =
                menuMapper.selectPermsByUserId(user.getId());


        // 04 封装UserDetails对象返回

        return new LoginUser(user, permissionKeyList);
    }
}
